package com.yyc.stocktake2.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.yyc.stocktake2.R
import com.yyc.stocktake2.base.BaseFragment
import com.yyc.stocktake2.bean.AppRoomDataBase
import com.yyc.stocktake2.databinding.FAssetSearchBinding
import com.yyc.stocktake2.ext.showMessage
import com.yyc.stocktake2.ext.showToast
import com.yyc.stocktake2.util.MusicUtils
import com.yyc.stocktake2.viewmodel.AssetSearchmModel
import com.yyc.stocktake2.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * @Author nike
 * @Date 2023/8/2 14:17
 * @Description
 */
class AssetSearchFrg: BaseFragment<AssetSearchmModel, FAssetSearchBinding>() {

    val rfidModel: RfidModel by activityViewModels()

    val assetSearchmModel: AssetSearchmModel by activityViewModels()

    var LabelTag: String? = null

    val mHandler = Handler(Looper.getMainLooper())

    val configDao = AppRoomDataBase.get().getConfigDao()

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            val jsonObject = JSONObject(it.getString("bean"))
            LabelTag = jsonObject.optString("LabelTag")
        }
        MusicUtils.init(activity)
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()

        mDatabind.circularProgressBar.onProgressChangeListener = { progress ->
            runOnUiThread {
                mViewModel.rssi.set("${progress.toInt()}")
            }
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                stop()
                mViewModel.isOpen.set(false)
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                stop()
                mViewModel.isOpen.set(false)
                assetSearchmModel.epcData.value = null
                MusicUtils.clear()
                mHandler.removeCallbacksAndMessages(null)
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        assetSearchmModel.epcData.observe(viewLifecycleOwner, Observer {
            if (it == null || !LabelTag.equals(it.tagId))return@Observer
            var rssi = it.rssi?.replace("-", "")!!.toDouble()

            /*mDatabind.circularProgressBar.progress = rssi!!.toFloat()
            runOnUiThread {
                mDatabind.circularProgressBar.setProgressWithAnimation(rssi!!.toFloat(), 1000)
            }*/

            mHandler.removeCallbacks(delayTask)
            runOnUiThread {
                mDatabind.scSignal.setRssi(rssi.toInt())

                var rssi = rssi.toInt()
                when {
                    rssi in 1..35 -> {
                        MusicUtils.setPlayCount(3)
                        MusicUtils.setSpeechRate(2.0f)
                    }
                    rssi in 36..49 -> {
                        MusicUtils.setPlayCount(2)
                        MusicUtils.setSpeechRate(1.5f)
                    }
                    /*rssi in 50..59 -> {

                    }
                    rssi in 60..69 -> {

                    }
                    rssi > 70 -> {

                    }*/
                    else -> {
                        MusicUtils.setPlayCount(1)
                        MusicUtils.setSpeechRate(1.0f)
                    }
                }
                MusicUtils.play()
                mHandler.postDelayed(delayTask, 2000)
            }
        })
    }

    // 定义一个延迟任务的 Runnable
    val delayTask = Runnable {
        mDatabind.scSignal.setRssi(0)
    }

    inner class ProxyClick() {

        fun start(){
            if (StringUtils.isEmpty(LabelTag) || LabelTag.equals("null")){
                showMessage(message = getString(R.string.no_labelTag))
                return
            }
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val configBean = configDao.findFirst()
                configBean.powerType = 1
                configDao.update(configBean)
            }
            if (mViewModel.isOpen.get()){
                stop()
            }else{
                rfidModel.isSearchOpen.value = LabelTag
                mViewModel.openStatus.set(getString(R.string.stop))
            }
            mViewModel.isOpen.set(!mViewModel.isOpen.get())
        }

    }

    private fun stop() {
        rfidModel.isSearchOpen.value = null
        mViewModel.openStatus.set(getString(R.string.start))
    }

}